package com.example.interceptor;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.example.annotation.LoginToken;
import com.example.annotation.PassToken;
import com.example.entity.User;
import com.example.result.Code;
import com.example.result.Message;
import com.example.result.R;
import com.example.service.IUserService;
import com.example.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Date 2022/10/4
 * @Description
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JWTUtils jwtUtils;

    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (Strings.isBlank(token)) {
            R r = R.fail(Code.TOKEN_ERROR_CODE, Message.NOT_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(r));
            return false;
        }
        Claims claims = jwtUtils.parseToken(token);
        if (claims == null) {
            R r = R.fail(Code.TOKEN_ERROR_CODE, Message.TOKEN_ERROR);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(r));
            return false;
        }

//        User user = userService.getById(claims.getSubject());
//        Assert.notNull(user, Message.NOT_LOGIN);

        return true;
    }

}
